package dyyx;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public abstract class FileUtil {

	private static final String UTF8 = "utf8";

	public static final String INDEX_DIR = "/tmp/lucenedemo/";
	public static final String DATA_FILE = "data/data.txt";

	public static void main(String[] args) throws Exception {
		System.out.println("hello,FileUtil," + new Date());
		String file = "data/data.txt";
		List<String> list = readLinesFromResource(file, null);
		for (String item : list) {
			System.out.println(item);
		}

		System.out.println(list.size());

	}

	public static List<String> readLinesFromResource(String name, String charset) throws Exception {
		String str = readStringFromResource(name, charset);
		if (StringUtils.isBlank(str)) {
			return null;
		}
		String[] arr = StringUtils.split(str, "\n");
		if (arr == null || arr.length <= 0) {
			return null;
		}
		List<String> list = new ArrayList<String>();
		for (String item : arr) {
			if (StringUtils.isBlank(item)) {
				continue;
			}
			item = item.trim();
			list.add(item);
		}

		return list;
	}

	public static String readStringFromResource(String name, String charset) throws Exception {
		byte[] bytes = readBytesFromResource(name);
		if (StringUtils.isBlank(charset)) {
			charset = UTF8;
		}
		return new String(bytes, charset);
	}

	public static byte[] readBytesFromResource(String name) throws Exception {
		InputStream is = null;
		try {
			is = FileUtil.class.getResourceAsStream(name);

			// is = CommUtil.class.getClassLoader().getResourceAsStream(name);

			if (is == null) {
				is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
			}

			if (is == null) {
				throw new Exception("resource not find,name=" + name);
			}
			return toBytes(is);
		} finally {
			close(is);
		}
	}

	private static byte[] toBytes(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int tmp = 0;
		while ((tmp = is.read()) != -1) {
			bos.write(tmp);
		}
		return bos.toByteArray();
	}

	public static void close(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (Throwable e) {

		}
	}

}
